//
//  WeChatInputView 2.h
//  MiniWeChat
//
//  Created by ByteDance on 2025/6/28.
//


#import "WXInputView.h"
#import "Masonry.h"

@interface WXInputView ()

@property(nonatomic, strong) NSIndexPath *originIndexPath;

@end

@implementation WXInputView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubviews];
        [self setupConstraints];
        [self setupNotifications];
    }
    return self;
}

- (void)setupSubviews {
    self.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    
    // 创建文本视图
    self.textView = [[UITextView alloc] init];
    self.textView.delegate = self;
    self.textView.font = [UIFont systemFontOfSize:16];
    self.textView.backgroundColor = [UIColor whiteColor];
    self.textView.layer.cornerRadius = 5;
    self.textView.layer.masksToBounds = YES;
    self.textView.returnKeyType = UIReturnKeySend;
    self.textView.enablesReturnKeyAutomatically = YES;
    [self addSubview:self.textView];
    
    // 创建发送按钮
    self.sendButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [self.sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.sendButton.backgroundColor = [UIColor colorWithRed:0/255.0 green:135/255.0 blue:255/255.0 alpha:1.0];
    self.sendButton.layer.cornerRadius = 5;
    self.sendButton.layer.masksToBounds = YES;
    [self.sendButton addTarget:self action:@selector(sendButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.sendButton];
    
    // 设置默认高度
    self.minHeight = 50;
    self.maxHeight = 120;
}

- (void)setupConstraints {
    // 禁用自动转换
    self.textView.translatesAutoresizingMaskIntoConstraints = NO;
    self.sendButton.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.greaterThanOrEqualTo(@(self.minHeight - 16)); // 高
        make.leading.equalTo(self).offset(10); // 左
        make.top.equalTo(self).offset(8); // 顶
        make.bottom.equalTo(self).offset(-8); // 底
    }];
    
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@60); // 宽
        make.height.equalTo(@(self.minHeight - 16)); // 高
        make.leading.equalTo(self.textView.mas_trailing).offset(10); // 左
        make.trailing.equalTo(self).offset(-10); // 右
        make.bottom.equalTo(self).offset(-8); // 底
    }];
}

- (void)setupNotifications {
    // 监听键盘事件
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {
    // 1. 计算文本高度
    CGSize size = [textView sizeThatFits:CGSizeMake(textView.bounds.size.width, CGFLOAT_MAX)];
    CGFloat newHeight = size.height + 16; // 加上内边距
    
    // 限制最大高度，超过则显示滚动条
    if (newHeight > self.maxHeight) {
        newHeight = self.maxHeight;
    } else if (newHeight < self.minHeight) {
        newHeight = self.minHeight;
    }
    
    // 更新输入框高度
    if (newHeight != self.bounds.size.height) {
        CGRect frame = self.frame;
        CGFloat diff = newHeight - self.frame.size.height;
        frame.size.height += diff;
        frame.origin.y -= diff;
        self.frame = frame;
        
        // 通知父视图更新布局
        if ([self.superview respondsToSelector:@selector(setNeedsLayout)]) {
            [self.superview setNeedsLayout];
            [self.superview layoutIfNeeded];
        }
    }
}

#pragma mark - 键盘处理

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *keyboardFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [keyboardFrameValue CGRectValue];
    keyboardFrame = [self convertRect:keyboardFrame fromView:nil];
    
    NSNumber *animationDuration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *animationCurve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    [UIView animateWithDuration:[animationDuration doubleValue]
                          delay:0
                        options:([animationCurve integerValue] << 16)
                     animations:^{
        // 1. 调整输入框位置
        CGRect frame = self.frame;
        frame.origin.y -= keyboardFrame.size.height;
        self.frame = frame;
        // 2. 调整 TableView 高度
        for (UIView *view in self.superview.subviews) {
            if ([view isKindOfClass:[UITableView class]]) {
                CGRect _frame = view.frame;
                _frame.size.height -= keyboardFrame.size.height;
                view.frame = _frame;
                UITableView *tableView = (UITableView *)view;
                // 3. 默认展示当前界面的最后一条数据
                // 滚动到当前界面的最后一条数据 UITableViewScrollPositionBottom 表示滚动到该行底部显示
                self.originIndexPath = [tableView indexPathsForVisibleRows].lastObject;
                [tableView scrollToRowAtIndexPath:self.originIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
        }
    } completion:nil];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *keyboardFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [keyboardFrameValue CGRectValue];
    keyboardFrame = [self convertRect:keyboardFrame fromView:nil];
    
    NSNumber *animationDuration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *animationCurve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    [UIView animateWithDuration:[animationDuration doubleValue]
                          delay:0
                        options:([animationCurve integerValue] << 16)
                     animations:^{
        // 1. 调整输入框位置
        CGRect frame = self.frame;
        frame.origin.y += keyboardFrame.size.height;
        self.frame = frame;
        // 2. 调整 TableView 高度
        for (UIView *view in self.superview.subviews) {
            if ([view isKindOfClass:[UITableView class]]) {
                CGRect _frame = view.frame;
                _frame.size.height += keyboardFrame.size.height;
                view.frame = _frame;
                UITableView *tableView = (UITableView *)view;
                // 3. 默认展示当前界面的最后一条数据
                // 滚动到当前界面的最后一条数据 UITableViewScrollPositionBottom 表示滚动到该行底部显示
                [tableView scrollToRowAtIndexPath:self.originIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
        }
    } completion:nil];
}

#pragma mark - 发送按钮

- (void)sendButtonTapped {
    NSString *text = self.textView.text;
    if (text.length <= 0) return;
    
    // 1.调用回调
    if (self.sendBlock) self.sendBlock(text);
    
    // 2.清空文本
    self.textView.text = @"";
    
    // 3.高度更新
    [self textViewDidChange:self.textView];
}

@end
